package io.renren.modules.job.task;

import io.renren.common.enums.CommonProcessStatus;
import io.renren.modules.customer.entity.MessageReplyEntity;
import io.renren.modules.customer.entity.MessageRequestEntity;
import io.renren.modules.customer.service.MessageReplyService;
import io.renren.modules.customer.service.MessageRequestService;
import io.renren.thirdparty.sms.SmsApiClient;
import io.renren.thirdparty.sms.domain.QueryResponse;
import io.renren.thirdparty.sms.domain.QueryResultItem;
import io.renren.thirdparty.sms.enums.RequestStatusType;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 用户上行内容查询
 *
 * @author sean
 * @since 2020-03-22
 */
@Component("smsReplyQueryTask")
public class SmsReplyQueryTask extends SmsSendingReportQueryTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsReplyQueryTask.class);

    @Autowired
    private MessageReplyService messageReplyService;

    @Override
    public void run(String params) {
        //查询上行报告
        QueryResponse queryResponse = this.smsApiClient.mo();
        if (queryResponse == null || queryResponse.getStatus() != RequestStatusType.SUCCESS) {
            LOGGER.error("Fail to get mo data from vendor due to {}", queryResponse == null || queryResponse.getStatus() == null ? "未知错误" : queryResponse.getStatus().getDescription());
        } else {
            LOGGER.info("Current balance is {}", queryResponse.getBalance());
            this.updateStatusOrMoData(queryResponse.getItems());
        }
    }

    /**
     * 更新
     * @param items
     */
    public void updateStatusOrMoData(List<QueryResultItem> items) {
        if (items == null || items.size() < 1) {
            return;
        }
        for (QueryResultItem item : items) {
            if (item != null) {
                MessageRequestEntity requestEntity = this.messageRequestService.getByVendorMessageIdAndPhone(item.getMessageId(), item.getMobile());
                if (requestEntity != null) {
                    LOGGER.debug("Fount message request entity with id {} by message id {} & mobile phone {}", requestEntity.getId(), item.getMessageId(), item.getMobile());
                    this.updateRequestEntity(requestEntity, item);
                }
            }
        }
    }

    /**
     * 更新，查询结果有可能是状态报告，也有可能是上行报告
     * @param requestEntity
     * @param item
     */
    private void updateRequestEntity(MessageRequestEntity requestEntity, QueryResultItem item) {
        if(item.getIsStatusReport()) {
            //发送状态
            super.updateStatusReport(requestEntity, item);
        } else {
            //上行报告
            if (requestEntity.getRequestStatus() != CommonProcessStatus.SUCCESS) {
                requestEntity.setRequestStatus(CommonProcessStatus.SUCCESS);
                String responseContent = null;
                try {
                    responseContent = this.objectMapper.writeValueAsString(item);
                } catch (Exception e) {
                    LOGGER.error("Fail to write value as json", e);
                    responseContent = item.toString();
                }
                requestEntity.setResponseContent(responseContent);
                if (requestEntity.getRequestTime() == null) {
                    requestEntity.setRequestTime(item.getTime());
                    requestEntity.setRequestCount(requestEntity.getRequestCount() + 1);
                }
                this.messageRequestService.updateById(requestEntity);
            }
            if (StringUtils.isNotBlank(item.getContent())) {
                //更新上行报告
                MessageReplyEntity replyEntity = this.messageReplyService.getByVendorMessageIdAndPhone(item.getMessageId(), item.getMobile());
                if (replyEntity == null) {
                    replyEntity = new MessageReplyEntity();
                    replyEntity.setCreateTime(new Date());
                    replyEntity.setCreateUserId(requestEntity.getCreateUserId());
                    replyEntity.setBatchNumber(requestEntity.getBatchNumber());
                    replyEntity.setMessageId(item.getMessageId());
                    replyEntity.setMobilePhone(item.getMobile());
                    replyEntity.setReplyContent(item.getContent().trim());
                    replyEntity.setRequestCount(requestEntity.getRequestCount());
                    replyEntity.setRequestStatus(CommonProcessStatus.SUCCESS);
                    replyEntity.setRequestTime(requestEntity.getRequestTime());
                    replyEntity.setSendDate(requestEntity.getSendDate());
                    replyEntity.setSerialNumber(requestEntity.getSerialNumber());
                } else {
                    replyEntity.setReplyContent(item.getContent().trim());
                }
                if (replyEntity.getId() == null) {
                    this.messageReplyService.save(replyEntity);
                } else {
                    this.messageReplyService.updateById(replyEntity);
                }
            }
        }
    }
}
